//
//  DXBaseService.m
//  iDxyer
//
//  Created by sun black on 11-11-21.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "WCBaseService.h"


@implementation WCBaseService

@synthesize delegate=_delegate;

-(void)cancleAllWorkingRequest{
    [workingRequest makeObjectsPerformSelector:@selector(clearDelegatesAndCancel)];
}

-(void)requestSuccess:(ASIHTTPRequest *)request withJSON:(NSDictionary *)json{
    //do nothing,subclass should overwrite this method;
}

#pragma mark -ASIHTTPRequest Delegate
-(void)requestFinished:(ASIHTTPRequest *)request{
    [workingRequest removeObject:request];
    
    NSLog(@"req:%d", request.responseStatusCode);
    
    NSDictionary *dict = [request.responseString JSONValue];
    if(request.responseStatusCode<200 ||request.responseStatusCode>=400){
        NSLog(@"requestKey=%@",[request.userInfo objectForKey:kRequestTypeKey]);
        NSError *error = [NSError errorWithDomain:[NSString stringWithFormat:@"返回StatuCode=%d",request.responseStatusCode] code:-1 userInfo:nil];
        [self.delegate requestDidFailureWithError:error andUserInfo:request.userInfo];
        return;
        
    }
    if ([[dict objectForKey:@"idxyer_error"] intValue]!=0) {//等于0表示成功，也应该调用成功的回调
        //int errorCode = [[dict objectForKey:@"idxyer_error"] intValue];
        //NSString *errorMsg = [[DxyerAppContext sharedInstance] errorMessageForCode:errorCode];
        //NSError *error = [NSError errorWithDomain:errorMsg?:@"网络错误" code:errorCode?:-1 userInfo:nil];
        //[self.delegate requestDidFailureWithError:error andUserInfo:request.userInfo];
    }else{
        [self requestSuccess:request withJSON:dict];
    }
}
-(void)requestFailed:(ASIHTTPRequest *)request{
    NSLog(@"req:%@", request.url);
    [workingRequest removeObject:request];
    NSLog(@"requestKey=%@",[request.userInfo objectForKey:kRequestTypeKey]);
    NSError *error = [NSError errorWithDomain:@"网络超时或网络错误!" code:NETWORK_ERROR_CODE userInfo:nil];
    [self.delegate requestDidFailureWithError:error andUserInfo:request.userInfo];
}

#pragma mark - Life Cirycle
+(id)serviceWithDelegate:(id<ServiceDelegate>)delegate{
    return [[self alloc] initWithDelegate:delegate];
}

-(id)initWithDelegate:(id<ServiceDelegate>)delegate{
    if (self = [super init]) {
        self.delegate = delegate;
        workingRequest = [[NSMutableArray alloc] init];
        return self;
    }
    return nil;
}
-(id)init{
    return [self initWithDelegate:nil];
}
-(void)dealloc{
    [self cancleAllWorkingRequest];
}

@end
